from QQLoginTool.QQtool import OAuthQQ
from django.conf import settings
from itsdangerous import TimedJSONWebSignatureSerializer as TJS
# Create your views here.
from rest_framework import status
from rest_framework.generics import CreateAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework_jwt.settings import api_settings

from carts.utils import merge_cart_cookie_to_redis
from oauth.models import OauthQQUser
from oauth.serializers import QQAuthUserSerializer


class QQAuthURLView(APIView):
    def get(self, request):
        # next表示从哪个页面进入到的登录页面，将来登录成功后，就自动回到那个页面
        next = request.query_params.get("state")
        if not next:
            next = '/'

        # 获取QQ登录页面网址
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI, state=next)
        login_url = oauth.get_qq_url()
        return Response({"login_url": login_url})


class QQAuthUserView(CreateAPIView):
    serializer_class = QQAuthUserSerializer

    def get(self, request):
        # 获取code并且校验
        code = request.query_params.get("code")
        if not code:
            return Response({"message": "缺少code"}, status=status.HTTP_400_BAD_REQUEST)

        # 获取qq登录对象
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI)

        try:
            # 使用code向QQ服务器请求access_token
            access_token = oauth.get_access_token(code)

            # 使用access_token向QQ服务器请求openid
            openid = oauth.get_open_id(access_token)
        except Exception:
            return Response({"message": "服务器异常"}, status.HTTP_503_SERVICE_UNAVAILABLE)

        # 使用opneid查询是否绑定过美多商城
        try:
            qq_user = OauthQQUser.objects.get(openid=openid)
        except:
            # 没有绑定，创建用户并绑定到openid， 并且将openid加密返回给前端
            tjs = TJS(settings.SECRET_KEY, 300)
            openid = tjs.dumps({"openid": openid}).decode()
            return Response({"openid": openid})

        # 已绑定登录成功
        else:
            user = qq_user.user

            # 生成token返回
            # 生成token
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)

            response = Response({
                'token': token,
                'username': user.username,
                'user_id': user.id
            })
            # 合并购物车
            response = merge_cart_cookie_to_redis(request, response, user)

            return response
    # def post(self, request, *args, **kwargs):
